package com.example.shopping.controller;

import com.example.shopping.entity.Goods;
import com.example.shopping.entity.User;
import com.example.shopping.entity.Order;
import com.example.shopping.entity.dto.OrderDTO;
import com.example.shopping.service.GoodsService;
import com.example.shopping.service.GoodsTypeService;
import com.example.shopping.service.OrderService;
import com.example.shopping.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderService orderService;

    @GetMapping("/list")
    public String findAllUser(Model model){
        model.addAttribute("allUsers",userService.findAll());
        return "userList";
    }
    @GetMapping("/delete")
    public String deleteUser(@RequestParam("uid") int uid) {
        userService.deleteUserByUid(uid); // 调用删除方法

        return "redirect:/user/list"; // 删除完成后重定向到用户列表页
    }

    @GetMapping("/add")
    public String showAddUserForm(Model model) {
        String items[]= {"足球","旅游","游泳","读书","篮球"};
        String hobbycode[][]= new  String[5][2];
        for(int i=0;i<items.length;i++) {
            hobbycode[i][0]=items[i];
            hobbycode[i][1]="";
        }
        model.addAttribute("hobbycode",hobbycode);
        return "register"; // 返回 userAdd.html 页面
    }

    @PostMapping("/save")
    public String saveUser( User user) {


        userService.saveUser(user); // 调用服务层保存用户

        return "redirect:/user/list"; // 保存成功后跳转到用户列表页
    }


    @GetMapping("/edit")
    public String editUser(@RequestParam("uid") Integer uid, Model model) {
        // 查询用户信息逻辑
        User user = userService.findById(uid);
        model.addAttribute("user", user);

        String hobbys[]=user.getHobby().split(",");
        ArrayList alist=new ArrayList();
        for( int i=0;i<hobbys.length;i++) {
            alist.add(hobbys[i]);
        }
        String items[]= {"足球","旅游","游泳","读书","篮球"};
        String hobbycode[][]= new  String[5][2];

        for(int i=0;i<items.length;i++) {
            hobbycode[i][0]=items[i];
            if(alist.contains(items[i]))
                hobbycode[i][1]="checked";
            else
                hobbycode[i][1]="";
        }
        model.addAttribute("hobbycode", hobbycode);

        return "userEdit"; // 返回编辑页面
    }


    @PostMapping("/update")
    public String updateUser(User user) {
        userService.updateUser(user);
        // 实际开发中应调用 service 更新数据库
        return "redirect:/user/list"; // 修改成功后重定向回编辑页
    }


    @GetMapping("/pageList")
    public String userList(@RequestParam(defaultValue = "1") int page, Model model) {

        Pageable pageable = PageRequest.of(page - 1, 5); // 每页 5 条记录
        // 假设你有一个 UserService 来获取分页数据
        Page<User> userPage = userService.findAllUser(pageable); // 每页 5 条记录

        model.addAttribute("allUsers", userPage.getContent());
        model.addAttribute("currentPage", userPage.getNumber() + 1);
        model.addAttribute("totalPages", userPage.getTotalPages());
        model.addAttribute("totalItems", userPage.getTotalElements());

        return "userPageList";
    }


    // 用户综合查询页面
    @PostMapping("/query")
    public String userQueryPost(Model model,
                            @RequestParam(value = "username", required = false, defaultValue = "") String username,
                            @RequestParam(value = "mailingaddress", required = false, defaultValue = "") String mailingaddress,
                            @RequestParam(value = "ssex", required = false, defaultValue = "") String ssex,
                            @RequestParam(value = "pageno", required = false, defaultValue = "1") int pageNo) {

        int pageSize = 5; // 每页显示的记录数
        Page<User> page = userService.queryUsers(username, mailingaddress, ssex, pageNo, pageSize);

        model.addAttribute("users", page.getContent());
        model.addAttribute("currentPage", pageNo);
        Integer totalPages= page.getTotalPages();
        model.addAttribute("totalPages", totalPages == null ? 1 : totalPages);
        model.addAttribute("totalItems", page.getTotalElements());
        model.addAttribute("username", username);
        model.addAttribute("mailingaddress", mailingaddress);
        model.addAttribute("ssex", ssex);
        model.addAttribute("pagesize", pageSize);

        return "userQuery";
    }

    // 处理 GET 请求（页面首次打开、分页等）
    @GetMapping("/query")
    public String userQueryGet(Model model) {
        model.addAttribute("totalPages", 1);
        return "userQuery";
    }


//跳转到购买页面
    @GetMapping("/buy")
    public String userBuyGet(Model model) {
        model.addAttribute("allGoodsType",goodsTypeService.findAll());
        model.addAttribute("totalPages",1);
        return "userBuy";
    }

    //购买页面，商品查询
    @PostMapping("/buy/query")
    public String queryGoods(
            @RequestParam(required = false) String goodsname,
            @RequestParam(required = false) String gid,
            @RequestParam(required = false) String goodstype,
            @RequestParam(value = "pageno",defaultValue = "1") int pageNo,
            Model model) {
        model.addAttribute("allGoodsType",goodsTypeService.findAll());


        // 安全处理空字符串
        if (goodsname != null && goodsname.trim().isEmpty()) {
            goodsname = null;
        }
        if (gid != null && gid.trim().isEmpty()) {
            gid = null;
        }
        if (goodstype != null && goodstype.trim().isEmpty()) {
            goodstype = null;
        }




        Map<String, Object> para = new HashMap<>();
        para.put("goodsname", goodsname);
        para.put("gid", gid);
        para.put("tcode", goodstype);

        model.addAttribute("para", para);

        model.addAttribute("map", goodsTypeService.findAllGoodsTypeAsMap());
        int pageSize=5;

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        model.addAttribute("pageSize",pageSize);


        Page<Goods> goodsPage = goodsService.findGoods(goodsname,gid,goodstype,pageable); // 这里应调用 goodsRepository 查询

        model.addAttribute("goods", goodsPage.getContent());
        model.addAttribute("pageNo", pageNo);
        Integer totalPages= goodsPage.getTotalPages();
        model.addAttribute("totalPages", totalPages== null ? 1 : totalPages );


        model.addAttribute("currentPage", goodsPage.getNumber() + 1); // 当前页码（从 1 开始）
        model.addAttribute("totalCount", goodsPage.getTotalElements()); // 总记录数




        return "userBuy";
    }



    @GetMapping("/buy/update")
    public ResponseEntity<OrderDTO> buy(@RequestParam Map<String, String> requestParams , HttpServletRequest request) {
        // 提取请求参数
        String gid = requestParams.get("gid");
        String goodsname = requestParams.get("goodsname");
        Double money = Double.parseDouble(requestParams.get("money"));
        Float price = Float.parseFloat(requestParams.get("price"));
        Integer quantity = Integer.parseInt(requestParams.get("quantity"));
        String receiver = requestParams.get("receiver");
        String rphone = requestParams.get("rphone");
        String mailingaddress = requestParams.get("mailingaddress");
        LocalDateTime buytime = LocalDateTime.now();

        // 获取 session 对象
        HttpSession session = request.getSession();

        // 获取 session 中的属性
        User user =(User) session.getAttribute("loginUser");
        int uid = user.getUid();

        // 调用下单服务
        Order order = orderService.createOrder(uid,gid, quantity ,money, buytime, rphone, mailingaddress, receiver,price);

        OrderDTO dto = new OrderDTO();
        BeanUtils.copyProperties(order,dto );
        dto.setGoodsname(goodsname);

        // 返回订单信息给前端
        return ResponseEntity.ok(dto);
    }



    @GetMapping("/login")
    public String showLoginForm() {
        return "login"; // 返回 login.html 页面
    }


    @PostMapping("/login")
    public String handleLogin(@RequestParam int uid,
                              @RequestParam String password,
                              Model model, HttpSession session) {


        User u=userService.authenticate(uid, password);
        // TODO: 实际应调用服务层验证用户名和密码
        if (u.getPassword().equals(password)) {
            session.setAttribute("loginUser", u);
            return "header"; // 登录成功跳转到hdeader.html
        } else {
            model.addAttribute("error", true);
            return "login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate(); // 清除 session
        return "redirect:/user/login";
    }

}
